<template>
  <a-popover placement="left" trigger="hover">
    <template #title>
      <div style="display: flex">
        <div style="flex: 1">自定义列</div>
        <a>
          <a-icon type="reload" @click="init"/>
        </a>
      </div>
    </template>
    <a>
      <a-icon type="setting"/>
    </a>
    <template slot="content">
      <div @dragover.prevent.stop="stop">
        <div class="h-table-column-setting-item"
             @click="() => changeSelected(item)" draggable="true"
             @dragstart="(e) => dragstart(e, item)"
             @dragover.prevent.stop="(e) => dragover(e, item)"
             @dragend="(e) => dragend(e, item)"
             :key="item.columnKey" v-for="(item, index) in realSortedColumns">
          <div style="flex: 1">
            <a-checkbox
              style="margin-right: 10px"
              :checked="realSelectedColumnKeys.indexOf(item.columnKey) !== -1"/>
            {{ item.title }}
          </div>
          <a @click.stop="() => moveUp(index)" v-show="index !== 0"><a-icon type="arrow-up" /></a>
          <a @click.stop="() => moveDown(index)" v-show="index !== realSortedColumns.length - 1" style="margin-left: 5px"><a-icon type="arrow-down" /></a>
        </div>
      </div>
    </template>
  </a-popover>

</template>
<script>
import {createProps} from '@/utils/CommonUtils';

function stop(e) {
  e && e.preventDefault();
}
export default {
  name: 'ColumnsSetting',
  props: {
    componentKey: createProps(String),
    colums: createProps(Array)
  },
  data() {
    return {
      selectedColumnKeys: [],
      sortedColumnKeys: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      let temp = localStorage.getItem(this.componentKey);
      // console.log(this.componentKey, temp, 'read')
      if (temp) {
        temp = JSON.parse(temp);
        this.selectedColumnKeys = temp.selectedColumnKeys || [];
        this.sortedColumnKeys = temp.sortedColumnKeys || [];
      }
    });
  },
  methods: {
    init() {
      this.selectedColumnKeys = [];
      this.sortedColumnKeys = [];
    },
    dragend(e) {
      e.preventDefault();
      e.stopPropagation();
      document.body.style.removeProperty('cursor')
    },
    changeSelected(item) {
      let res = [...this.getRealSelectedColumnKeys()];
      let index = res.indexOf(item.columnKey);
      if (index !== -1) {
        res.splice(index, 1);
      } else {
        res.push(item.columnKey);
      }
      if (!res.length) return;
      this.selectedColumnKeys = res;
    },
    moveUp(index) {
      let temp = this.sortedColumnKeys[index]
      this.sortedColumnKeys[index] = this.sortedColumnKeys[index - 1]
      this.sortedColumnKeys[index - 1] = temp

      this.sortedColumnKeys = [...this.sortedColumnKeys]
    },
    moveDown(index) {
      let temp = this.sortedColumnKeys[index]
      this.sortedColumnKeys[index] = this.sortedColumnKeys[index + 1]
      this.sortedColumnKeys[index + 1] = temp

      this.sortedColumnKeys = [...this.sortedColumnKeys]
    },
    getRealSelectedColumnKeys() {
      if (!this.selectedColumnKeys || !this.selectedColumnKeys.length) {
        return this.colums.map(c => c.columnKey);
      }
      return this.selectedColumnKeys || [];
    },
    getRealSortedColumnKeys() {
      if (!this.sortedColumnKeys
        || !this.sortedColumnKeys.length
        || this.sortedColumnKeys.length !== this.colums.length) {
        return this.colums.map(c => c.columnKey);
      }
      return this.sortedColumnKeys || [];
    },
    dragstart(e, item) {
      this.draggingItemKey = item.columnKey;
    },
    dragover(e, item) {
      e.preventDefault();
      let columnKey = item.columnKey;
      if (columnKey === this.draggingItemKey) return;
      let list = this.getRealSortedColumnKeys();
      let index = list.indexOf(columnKey);
      list = list.filter(k => k !== this.draggingItemKey);
      list.splice(index, 0, this.draggingItemKey);
      this.sortedColumnKeys = list;
    },
    stop,
    getRealSortedColumns() {
      let keys = this.getRealSortedColumnKeys();
      let res = [];
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        let item = this.colums.find(i => i.columnKey === key);
        item && res.push(item);
      }
      return res;
    },
    columnsChange() {
      let keys = this.getRealSelectedColumnKeys();
      let columns = this.getRealSortedColumns();
      let res = [];
      for (let i = 0; i < columns.length; i++) {
        let column = columns[i];
        if (keys.indexOf(column.columnKey) !== -1) {
          res.push(column);
        }
      }
      this.saveData();
      this.$emit('change', res);
    },
    saveData() {
      let data = {
        selectedColumnKeys: this.getRealSelectedColumnKeys(),
        sortedColumnKeys: this.getRealSortedColumnKeys()
      };
      // debugger
      // console.log(this.componentKey, JSON.stringify(data), 'write')
      localStorage.setItem(this.componentKey, JSON.stringify(data));
    },
  },
  computed: {
    realSelectedColumnKeys() {
      return this.getRealSelectedColumnKeys();
    },
    realSortedColumns() {
      let keys = this.getRealSortedColumnKeys();
      let res = [];
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        let item = this.colums.find(i => i.columnKey === key);
        item && res.push(item);
      }
      return res;
    },
  },
  watch: {
    sortedColumnKeys: {
      handler() {
        this.columnsChange();
      },
      immediate: false
    },
    selectedColumnKeys: {
      handler() {
        this.columnsChange();
      },
      immediate: false
    },
    componentKey: {
      handler() {
        this.$nextTick(() => {
          this.columnsChange();
        })
      },
      immediate: false
    }
  }
};
</script>
<style>

.h-table-column-setting-item {
  display: flex;
  margin-bottom: 3px;
  user-select: none;
  cursor: pointer;
  min-width: 280px;
}
</style>